package cn.huiyunche.bms.backend.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class PoiUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(PoiUtil.class);

    /**
     * 导出excel文件
     * @param sheetName 表名 sheet名
     * @param listTitle 标题
     * @param listData  数据
     * @param response
     * @throws Exception
     */
    public static void exportExcel(String sheetName, List listTitle, List<List> listData, HttpServletResponse response) throws Exception {
        LOGGER.info("PoiUtil.exportExcel params : {}, {}", listData);
        if (sheetName == null){
            LOGGER.error("PoiUtil.exportExcel param sheetName must not be null ");
            throw new IllegalArgumentException("表名不能为空");
        }
        if (listTitle.size()<=0) {
            LOGGER.error("PoiUtil.exportExcel param listTitle must not be null ");
            throw new IllegalArgumentException("标题不能为空");
        }
        if (listData.size()<=0) {
            LOGGER.error("PoiUtil.exportExcel param listData must not be null ");
            throw new IllegalArgumentException("导出数据不能为空");
        }
        //创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();
        //建立新的sheet对象（excel的表单）
        HSSFSheet sheet=wb.createSheet(sheetName);
        sheet.setColumnWidth(0, 10 * 256);
        //设置单元格列宽
        for (int i=1;i<listTitle.size()+1;i++){
            sheet.setColumnWidth(i, 10 * 512);
        }
        //在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
        HSSFRow row1=sheet.createRow(0);
        //创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
        HSSFCell cell=row1.createCell(0);
        //设置单元格内容
        cell.setCellValue(sheetName);
        //合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
        sheet.addMergedRegion(new CellRangeAddress(0,0,0,listTitle.size()));
        //在sheet里创建第二行
        HSSFRow row2=sheet.createRow(1);
        HSSFCell cell2 = row2.createCell(1);
        cell2.getCellStyle().setAlignment(HSSFCellStyle.ALIGN_CENTER);//居中
        //创建单元格并设置单元格内容
        row2.createCell((short)0).setCellValue("序号");
        for (int i=0;i<listTitle.size();i++){
            row2.createCell((short)i+1).setCellValue(listTitle.get(i).toString());
        }
        //在sheet里插入数据
        try {
            for(int i=0;i<listData.size();i++){
                HSSFRow hssfRow=sheet.createRow(i+2);
                hssfRow.createCell(0).setCellValue(i+1);
                for (int j=0;j<listData.get(i).size();j++){
                    if (listData.get(i).get(j) != null)
                        hssfRow.createCell(j+1).setCellValue(listData.get(i).get(j).toString());
                }
            }
        } catch (Exception e) {
            LOGGER.error("PoiUtil.exportExcel param listData insert excel error ");
            throw new IllegalArgumentException("插入excel数据异常！");
        }
        try {
            //弹出下载框
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
            String filename = sheetName + format.format(new Date());
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            wb.write(os);
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            // 设置response参数，可以打开下载页面
            filename = URLEncoder.encode(filename, "UTF-8");
            response.reset();
            response.setContentType("application/vnd.ms-excel; charset=utf-8");
            response.setHeader("Content-Disposition","attachment;filename="+ filename +".xls");
            response.setCharacterEncoding("utf-8");
            OutputStream out=response.getOutputStream();
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {
                bis = new BufferedInputStream(is);
                bos = new BufferedOutputStream(out);
                byte[] buff = new byte[2048];
                int bytesRead;
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null)
                    bis.close();
                if (bos != null)
                    bos.close();
            }
//            JOptionPane.showMessageDialog(null, "导出成功!");
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        }
    }
}
